package com.zhanghe.pipeline;

import com.zhanghe.handler.HttpController;
import com.zhanghe.handler.HttpHanlder;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

public class AllocHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

	/**
	 * 异常处理
	 */
	@Override
	public void exceptionCaught( ChannelHandlerContext ctx ,Throwable cause ) throws Exception {
		sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
		super.exceptionCaught(ctx, cause);
	}
	@Override
	protected void channelRead0( ChannelHandlerContext ctx ,FullHttpRequest msg ) throws Exception {
		//获取httphandler
		HttpHanlder httpHandler = HttpController.getHandler(msg.uri());
		if(httpHandler!=null){
			Object obj = httpHandler.excute(msg);
			if(obj instanceof String){
				sendMessage(ctx, obj.toString());
			}else{
				sendMessage(ctx, obj.toString());
			}
		}else{
			sendError(ctx, HttpResponseStatus.NOT_FOUND);
		}
	}
	/**
	 * 
	 * 功能：发送信息到response里面<br/>
	 * @param ctx
	 * @param msg
	 * @exception   无
	 * @since   	首次创建（zhanghe  2018-5-24)<br/>
	 *
	 */
	private void sendMessage(ChannelHandlerContext ctx, String msg) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, 
        		Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        response.headers().set("Content-Type", "text/plain");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
	/**
	 * 
	 * 功能：发送错误信息<br/>
	 * @param ctx
	 * @param httpResponseStatus
	 * @exception   无
	 * @since   	首次创建（zhanghe  2018-5-24)<br/>
	 *
	 */
    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus httpResponseStatus) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus, 
        		Unpooled.copiedBuffer(httpResponseStatus.toString(), CharsetUtil.UTF_8));
        response.headers().set("Content-Type", "text/plain");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
